<template>
  <div class="page-container">
    <div class="checkout-container">
      <a-page-header title="Shopping Bag" sub-title="Please confirm your order information"/>

      <!-- 步骤条 -->
      <a-steps :current="currentStep" class="checkout-steps">
        <a-step title="Confirm the order" description="Confirm product information"/>
        <a-step title="Select an address" description="Select delivery address and payment method"/>
        <a-step title="Pay order" description="Complete payment"/>
        <a-step title="complete" description="Payment successfully"/>
      </a-steps>

      <!-- 第一步：确认订单 -->
      <checkout-step1
          v-if="currentStep === 0"
          :selected-items="selectedItems"
          :current-step="currentStep"
          @update:step="updateStep"
          @update:items="updateItems"
      />

      <!-- 第二步：选择地址和支付方式 -->
      <checkout-step2
          v-else-if="currentStep === 1"
          :selected-items="selectedItems"
          :current-step="currentStep"
          @update:step="updateStep"
          @update:address="updateAddress"
          @update:addressId="updateAddressId"
          @update:payment="updatePayment"
          @update:shipping="updateShipping"
          @update:coupon="updateCoupon"
          @update:finalAmount="updateFinalAmount"
          @update:goodsAmount="updateGoodsAmount"
          @update:orderId="updateOrderId"
      />

      <!-- 第三步：支付 -->
      <checkout-step3
          v-else-if="currentStep === 2"
          :selected-items="selectedItems"
          :current-step="currentStep"
          :payment-method="paymentMethod"
          :address-id="selectedAddressId"
          :shipping-fee="shippingFee"
          :discount="couponInfo ? couponInfo.discount : 0"
          :final-amount="finalAmount"
          :goods-amount="goodsAmount"
          :order-id="orderId"
          @update:step="updateStep"
      />

      <!-- 第四步：完成 -->
      <checkout-step4
          v-else-if="currentStep === 3"
          :selected-items="selectedItems"
          :current-step="currentStep"
          :order-id="orderId"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { AlipayCircleOutlined, WechatOutlined, CreditCardOutlined } from '@ant-design/icons-vue';
import {Local, Session} from "@/utils/storage.ts";
import { getAddressList, addAddress, setDefaultAddress as setDefaultAddressApi } from "@/api/user";
import AddressForm from '@/components/common/AddressForm.vue';

// 直接导入步骤组件
import CheckoutStep1 from './CheckoutStep1.vue';
import CheckoutStep2 from './CheckoutStep2.vue';
import CheckoutStep3 from './CheckoutStep3.vue';
import CheckoutStep4 from './CheckoutStep4.vue';
import {getOrderDetail} from "@/api/order.js";

// 手动为每个组件设置名称，帮助调试
CheckoutStep1.name = 'CheckoutStep1';
CheckoutStep2.name = 'CheckoutStep2';
CheckoutStep3.name = 'CheckoutStep3';
CheckoutStep4.name = 'CheckoutStep4';

const router = useRouter();
const route = useRoute();

// 结算相关状态
const selectedAddressId = ref(null);
const paymentMethod = ref('alipay');
const shippingFee = ref(null);
const discount = ref(0); // 优惠金额
const couponInfo = ref(null); // 优惠券信息
const finalAmount = ref(0); // 最终金额
const submitting = ref(false);
const goodsAmount = ref(0) // 商品总金额

// 地址相关状态
const addresses = ref([]);
const addressModalVisible = ref(false);
const addressFormRef = ref(null);
const isPhoneValid = ref(false);

// 表单数据
const formData = ref({
  user_id: Local.get('userInfo')?.id || '',
  last_name: '',
  first_name: '',
  name: '',
  address: '',
  county: 'United States',
  province: '',
  city: '',
  zipcode: '',
  phone: '',
  countryCode: '+1',
  is_default: 0
});

// 默认地址状态
const isDefaultAddress = ref(false);

// 从路由参数获取选中的商品
const selectedItems = ref([]);
const selectedAddress = ref(null);
const orderId = ref('');

// 总价计算
const totalPrice = computed(() => {
  try {
    const total = selectedItems.value
        .filter(item => item && item.price && item.quantity)
        .reduce((sum, item) => {
          const price = Number(item.price) || 0;
          const quantity = Number(item.quantity) || 0;
          return sum + (price * quantity);
        }, 0);

    return total.toFixed(2);
  } catch (error) {
    console.error('计算总价出错:', error);
    return '0.00';
  }
});

// 当前步骤
const currentStep = ref(0);

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const res = await getAddressList({
      page: 1,
      page_size: 10
    });
    if (res.code === 200) {
      addresses.value = res.result.data || [];
      // 如果有默认地址，自动选中
      const defaultAddress = addresses.value.find(addr => addr.is_default === 1);
      if (defaultAddress) {
        selectedAddressId.value = defaultAddress.id;
      }
    }
  } catch (error) {
    console.error('获取地址列表失败:', error);
    message.error('获取地址列表失败，请稍后重试');
  }
};

// 显示添加地址模态框
const showAddAddressModal = () => {
  // 重置表单
  formData.value = {
    user_id: Local.get('userInfo')?.id || '',
    last_name: '',
    first_name: '',
    name: '',
    address: '',
    county: 'United States',
    province: '',
    city: '',
    zipcode: '',
    phone: '',
    countryCode: '+1',
    is_default: 0
  };
  isDefaultAddress.value = false;
  isPhoneValid.value = false;

  addressModalVisible.value = true;
};

// 表单数据更新处理
const onFormDataUpdate = (data) => {
  formData.value = { ...data };
};

// 默认地址更新处理
const onDefaultUpdate = (value) => {
  isDefaultAddress.value = value;
  formData.value.is_default = value ? 1 : 0;
};

// 电话验证状态更新
const onPhoneValidUpdate = (valid) => {
  isPhoneValid.value = valid;
};

// 保存地址
const saveAddress = async () => {
  if(!isPhoneValid.value && formData.value.phone) {
    message.error("电话号码格式不正确");
    return;
  }

  // 确保姓名和手机号被正确设置
  formData.value.name = `${formData.value.first_name} ${formData.value.last_name}`.trim();
  formData.value.zip_code = formData.value.zipcode;

  try {
    const valid = await addressFormRef.value.validate();
    if (!valid) {
      return;
    }

    const submitData = { ...formData.value };
    const res = await addAddress(submitData);

    if (res.code === 200) {
      message.success("地址添加成功");
      addressModalVisible.value = false;
      fetchAddresses(); // 重新获取地址列表

      // 如果添加的是默认地址，自动选中
      if (submitData.is_default === 1) {
        selectedAddressId.value = res.data?.id;
      }
    } else {
      message.error(res.message || "添加地址失败");
    }
  } catch (error) {
    console.error("添加地址失败:", error);
    message.error("操作失败，请稍后重试");
  }
};

// 设为默认地址
const handleSetDefaultAddress = async (address) => {
  try {
    const res = await setDefaultAddressApi(address.id);

    if (res.code === 200) {
      message.success(`${address.name} 已设为默认地址`);
      fetchAddresses(); // 重新获取地址列表
    } else {
      message.error(res.message || '设置默认地址失败');
    }
  } catch (error) {
    console.error('设置默认地址失败:', error);
    message.error('设置默认地址失败，请稍后重试');
  }
};

// 提交订单
const submitOrder = async () => {
  const selectedAddress = addresses.value.find(addr => addr.id === selectedAddressId.value);
  if (!selectedAddress) {
    message.error('请选择收货地址');
    return;
  }

  submitting.value = true;
  try {
    // 这里应该是提交订单的API调用
    await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟API调用

    // 进入支付步骤
    currentStep.value = 2;

    // 模拟支付过程
    setTimeout(() => {
      currentStep.value = 3;
      message.success('订单支付成功！');
      setTimeout(() => {
        router.push('/user/orders');
      }, 2000);
    }, 3000);
  } catch (error) {
    console.error('提交订单失败:', error);
    message.error('提交订单失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};

// 更新步骤
const updateStep = (step) => {
  currentStep.value = step;
};

// 更新商品数据
const updateItems = (items) => {
  selectedItems.value = items;
};

// 更新地址
const updateAddress = (address) => {
  selectedAddressId.value = address.id;
};

// 更新地址ID
const updateAddressId = (id) => {
  selectedAddressId.value = id;
};

// 更新支付方式
const updatePayment = (method) => {
  paymentMethod.value = method;
};

// 更新运费
const updateShipping = (fee) => {
  shippingFee.value = fee;
};

// 更新优惠券
const updateCoupon = (coupon) => {
  couponInfo.value = coupon;
};

// 更新最终金额
const updateFinalAmount = (amount) => {
  finalAmount.value = amount;
};

// 更新商品总额
const updateGoodsAmount = (amount) => {
  goodsAmount.value = amount;
};

const updateOrderId = (id) => {
  orderId.value = id;
};

// 初始化数据
const initData = () => {
  try {
    // 从localStorage获取商品数据
    const itemsStr = localStorage.getItem('selectedCheckoutItems');

    if (itemsStr) {
      try {
        // 使用JSON.parse解析localStorage中的数据
        const parsedItems = JSON.parse(itemsStr);

        if (Array.isArray(parsedItems) && parsedItems.length > 0) {
          // 确保每个商品都有必要的属性
          selectedItems.value = parsedItems.map(item => ({
            id: item.id,
            name: item.name || 'Unnamed products',
            specs: item.specs || 'Default specifications',
            price: Number(item.price) || 0,
            quantity: Number(item.quantity) || 1,
            image: item.image || '',
            goods_id: item.goods_id,
            sku_id: item.sku_id
          }));
        } else {
          selectedItems.value = [];
        }
      } catch (parseError) {
        console.error('JSON解析错误:', parseError);
        selectedItems.value = [];
      }
    } else {
      selectedItems.value = [];
    }
  } catch (error) {
    console.error('解析商品数据失败:', error);
    selectedItems.value = [];
  }

  if (route.query.step) {
    currentStep.value = parseInt(route.query.step);
  }
};

// 重新支付查询订单详情
const rePaymentInfo = ref(null);
const rePayment = async (id) => {
  try {
    const res = await getOrderDetail(id)
    if (res.code === 200) {
      rePaymentInfo.value = res.result;
      // 设置相关数据
      paymentMethod.value = rePaymentInfo.value.pay_method || '';
      finalAmount.value = Number(rePaymentInfo.value.pay_price) || 0;
      orderId.value = rePaymentInfo.value.id || '';
      goodsAmount.value = Number(rePaymentInfo.value.subtotal_price) || 0;

      // 处理商品信息
      if (rePaymentInfo.value.detail && rePaymentInfo.value.detail.length > 0) {
        selectedItems.value = rePaymentInfo.value.detail.map(item => ({
          id: item.id,
          name: item.goods_name || 'Unnamed product',
          specs: item.goods_name || 'Default specifications',
          price: Number(item.price) || 0,
          quantity: item.num || 1,
          image: item.image || '',
          goods_id: item.goods_id,
          sku_id: item.sku_id
        }));
      }

      // 处理运费和折扣信息
      shippingFee.value = {
        fee: Number(rePaymentInfo.value.freight) || 0,
        insuranceFee: Number(rePaymentInfo.value.freight_insurance) || 0,
        dutyInsuranceFee: Number(rePaymentInfo.value.tariff) || 0
      };

      discount.value = rePaymentInfo.value.discount_data.coupon_discount || 0;
    } else {
      message.error(res.msg || 'Failed to get order details')
    }
  } catch (error) {
    message.error('Failed to get order details, please try again later');
  }
}

// 监听路由变化
watch(() => route.query, (newQuery) => {
  initData();

  // 检查是否是重新支付流程
  if (newQuery.orderId && newQuery.step == '2') {
    // 获取订单信息
    rePayment(newQuery.orderId);
    currentStep.value = 2;
  }
}, { immediate: true });

// 组件挂载时获取地址列表和初始化数据
onMounted(() => {
  fetchAddresses();
  initData();
});
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 24px 0;
}

.checkout-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

.checkout-card {
  margin-top: 24px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.section {
  padding: 16px;
}

.section h3 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.product-price {
  color: #ff4d4f;
  font-weight: bold;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.address-radio {
  display: block;
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.address-info {
  margin-left: 8px;
}

.address-header {
  margin-bottom: 4px;
}

.address-header .name {
  font-weight: bold;
  margin-right: 8px;
}

.address-header .phone {
  color: #666;
  margin-right: 8px;
}

.address-detail {
  color: #999;
}

.payment-radio {
  margin-right: 24px;
}

.payment-icon {
  font-size: 24px;
  color: #1890ff;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.order-summary {
  background-color: #f9f9f9;
  padding: 16px;
  border-radius: 4px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.summary-row.total {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #ddd;
}

.checkout-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 16px;
}

.total-amount {
  font-size: 16px;
}

.highlight {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 20px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px 0;
  }

  .checkout-container {
    padding: 0 12px;
  }

  .checkout-footer {
    padding: 12px;
  }

  .total-amount {
    font-size: 14px;
  }

  .highlight {
    font-size: 18px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .address-radio {
    padding: 8px;
  }

  .address-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

.checkout-steps {
  margin: 24px 0;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .checkout-steps {
    margin: 16px 0;
    padding: 16px;
  }

  :deep(.ant-steps-item-title) {
    font-size: 12px;
  }

  :deep(.ant-steps-item-description) {
    font-size: 10px;
  }
}
</style>
